package dingding

import (
	"fmt"
	"os"

	"github.com/sirupsen/logrus"
)

// Hook 写文件的Logrus Hook
type Hook struct {
	WebHook string
	Phones  []string
}

// Fire 实现Hook的Fire接口
func (hook *Hook) Fire(entry *logrus.Entry) (err error) {
	message, err := getMessage(entry)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
		return err
	}
	switch entry.Level {
	case logrus.PanicLevel:
		fallthrough
	case logrus.FatalLevel:
		fallthrough
	case logrus.ErrorLevel:
		return postMessage(hook.WebHook, hook.Phones, fmt.Sprintf("[存储出错!] %s", message))
	case logrus.WarnLevel:
		return postMessage(hook.WebHook, hook.Phones, fmt.Sprintf("[存储警告!] %s", message))
	case logrus.InfoLevel:
		return postMessage(hook.WebHook, hook.Phones, fmt.Sprintf("[存储信息!] %s", message))
	case logrus.DebugLevel:
		return postMessage(hook.WebHook, hook.Phones, fmt.Sprintf("[存储调试!] %s", message))
	default:
		return nil
	}
}

// Levels 实现Hook的Levels接口
func (hook *Hook) Levels() []logrus.Level {
	return []logrus.Level{
		logrus.PanicLevel,
		logrus.FatalLevel,
		logrus.ErrorLevel,
		logrus.WarnLevel,
		logrus.InfoLevel,
		logrus.DebugLevel,
	}
}

func getMessage(entry *logrus.Entry) (message string, err error) {
	message = message + fmt.Sprintf("%s ", entry.Message)
	for k, v := range entry.Data {
		message = message + fmt.Sprintf("%v:%v ", k, v)
	}
	return
}
